import { message, notification, Tree, Modal, Form, Input, Button } from 'antd';
import { PlusCircleOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import React, { useEffect, useState } from 'react';
import $ from 'jquery';
import intl from 'react-intl-universal';
import '../classify/classify.css';


const ArticleClassify = (props) => {
  const [tempData, setTempData] = useState([]);                   // 后端接收数据
  const [classifyData, setClassifyData] = useState([]);           // 处理后的分类数据
  const [handleData, setHandleData] = useState(false);            // 是否处理tempData
  const [checkedKey, setCheckedKey] = useState([]);               // 编辑文章时，默认选中文章原有的分类；其他时候是当前选择的分类


  // 获取后台数据
  const [hasChange, setHasChange] = useState(true);
  useEffect(() => {
    const getClassification = () => {
      $.ajax({
        url: '/home/classify',
        type: 'post',
        dataType: 'json',
        success: function(result) {
          if (result.status === 1) {
            setTempData(result.data);
            setHandleData(true);
          } else {
            message.info(intl.get('failedToQuery'));
          }
        },
        error: function(err) {
          alert(JSON.stringify(err));
        },
      });
    };
    hasChange && getClassification();
    setHasChange(false);
  }, [hasChange]);


// 处理从后端接收的数据，成树形结构
const createTree = (data) => {
  let treeData = [];
  // 获取一级节点
  let roots = data.filter(element => element.parent === 0);
  treeData.push(...roots);
  // 从一级节点开始，获取每个元素的子元素放到该元素的children属性中
  const getChildren = (result, data) => {
    result.forEach((element, index) => {
      element.children = data.filter((item, index) => item.parent === element.kid);
      if (element.children.length > 0) {
        getChildren(element.children, data);
      }
    });
  }
  getChildren(treeData, data);
  return treeData;
};


// 再次处理数据，成官方文档中treeData格式
const createTreeData = (data) => {
  let treeData = [];
  data.map((item) => {
    let node = {
      key: item.kid,
      title: item.kname,
      children: createTreeData(item.children),
      description: item.kdescription,
      parent: item.parent,
      checkable: false,
    };
    if (node.children.length === 0)
      node.checkable = true;
    if (props.kind !== undefined && node.title === props.kind) {
      setCheckedKey([node.key]);
    }
    treeData.push(node);
  });
  return treeData;
};


  // 调用处理数据的方法
  useEffect(() => {
    let treeData = [];
    if (handleData) {
      treeData = createTree(tempData);
      treeData = createTreeData(treeData);
      setClassifyData(treeData);
    }
    setHandleData(false);
  }, [handleData]);


  // 获取选中的节点信息
  const onCheck = (key, e) => {
    // console.log(key)
    // console.log(e)
    if (key.length === 0)
      return;
    else {
      setCheckedKey([e.node.key]);
      props.setKind(e.node.title);
    }
  };


  return (
    <div style={{backgroundColor:'#fff'}}>
      {(classifyData.length > 0) ? 
        <Tree style={{margin:'20px 20px', fontSize:'16px'}} showLine={true} defaultExpandAll={true} autoExpandParent={true} 
        treeData={classifyData} checkable={true} onCheck={onCheck} checkedKeys={checkedKey} /> :
        <div />
      }
    </div>
  );
};

export default ArticleClassify;